<template>
  <div class="view">
    <div v-if="isLoading">加载中...</div>
    <div v-else>
      <div style="padding: 20px">
        <label>员工姓名：</label>
        <el-input placeholder="请输入员工姓名" style="width: 15%; margin-right:15px" v-model="name" clearable></el-input>
        <el-button type="primary" @click="pageQuery">查询</el-button>
        <el-button type="primary" style="float: right;" @click="addEmployee">+ 添加员工</el-button>
      </div>
      <el-table :data="records" stripe style="width: 100%; margin-top:20px">
        <el-table-column prop="name" label="员工姓名" width="180">
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="150">
          <template slot-scope="scope">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="账号" width="180">
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="180">
        </el-table-column>
        <el-table-column prop="status" label="账号状态" width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.status === 1">
              <i class="el-icon-success"> 启用</i>
            </span>
            <span v-if="scope.row.status === 0">
              <i class="el-icon-error">禁用</i>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后操作时间" width="180">
        </el-table-column>
        <el-table-column prop="status" label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" @click="edit(scope.row)">修改</el-button>
            <el-button type="text" @click="updataStatus(scope.row)">
              <span v-if="scope.row.status === 0">
                启用
              </span>
              <span v-if="scope.row.status === 1" style="color: #f56c6c;">
                禁用
              </span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="margin-top: 20px; text-align:center;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
          :page-sizes="[6, 10, 14, 18]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    <el-dialog title="修改员工信息" :visible.sync="dialogFormVisible">
      <el-form :model="form" class="update">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <br>
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth"><br>
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号" :label-width="formLabelWidth"><br>
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话号" :label-width="formLabelWidth"><br>
          <el-input v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateInfo()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      isLoading: true,
      name: '',
      page: 1,
      pageSize: 6,
      total: 0,
      records: [],
      dialogFormVisible: false,
      form: {
        id:'',
        name: '',
        gender: null,
        username: '',
        phone:''
      }
    }
  },
  created() {
    try {
      this.pageQuery()
    } finally {
      this.isLoading = false; 
    }
  },
  methods: {
    edit(row) {
      if (row.username !== this.$store.state.user.username) {
        this.$message.error("没有修改权限");
        return;
      }
      this.getById(row);
      this.dialogFormVisible = true;
    },
    updateInfo() {
      if (this.form.username !== this.$store.state.user.username ) {
        this.$message.error("没有修改权限")
      }
      this.$confirm('是否修改账号信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios({
          url: '/api/employee',
          method:'put',
          data: this.form,
          headers: {
            token:this.$store.state.user.token
          }
        }).then(res => {
          if (res.data.code === 1) {
            this.$message.success("信息修改成功！")
            this.pageQuery()
          }
          else {
            this.$message.error("修改失败，请稍后再试！")
          }
        })
        this.dialogFormVisible = false;
      })
    },
    getById(row) {
      axios({
        url: '/api/employee/getById',
        method: 'get',
        params: {
          id:row.id
        },
        headers: {
          token: this.$store.state.user.token
        }
      }).then(res => {
        if (res.data.code === 1) {
          this.form = res.data.data
        }
        else {
          this.$message.error("用户不存在！")
        }
      })
    },
    addEmployee() {
      this.$router.push('/home/employee/add')
    },
    handleError(err) {
      // 打印错误，方便调试
      console.error('An error occurred:', err);

      // 如果是 HTTP 错误
      if (err.response) {
        if (err.response.status === 401) {
          this.$message.error("您的登录已过期，请重新登录");
          this.$router.push('/login')
        } else if (err.response.status === 500) {
          this.$message.error("服务器异常，请稍后再试");
          this.$router.push('/404')
        } else {
          this.$message.error("请求失败");
        }
      } else if (err.request) {
        this.$message.error("网络错误，请检查您的网络连接");
      } else {
        this.$message.error("登录异常！请稍后再试~");
      }
    },
    pageQuery() {
      axios({
        url: '/api/employee/list',
        method: 'get',
        params: {
          name: this.name,
          page: this.page,
          pageSize:this.pageSize
        },
        headers: {
          token: this.$store.state.user.token
        }
      }).then(res => {
        if (res.data.code === 1) {
          console.log("请求成功");
          this.total = res.data.data.total,
          this.records = res.data.data.records
        }
        else if (res.data.code === 0) {
          this.$message.error('请求失败,请稍后再试')
        }
      }).catch(err => {
        this.handleError(err)
      })
    },
    // 页码发生变化时发送请求
    handleCurrentChange(page) {
      this.page = page
      this.pageQuery()
    },
    // 每页数量发生变化发送请求
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.pageQuery()
    },
    updataStatus(row) {
      if (row.username === 'admin') {
        this.$message.error("admin为超级管理员，不能禁用")
        return
      }
      if (this.$store.state.user.username !== 'admin') {
        this.$message.error("请登录管理员账号进行修改！")
        return
      }
      this.$confirm('是否修改员工状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const p = {
          id: row.id,
          status: !row.status ? 1 : 0
        }
        axios({
          url: `/api/employee/status/${p.status}`,
          method: 'post',
          params: {
            id:p.id
          },
          headers: {
            token:this.$store.state.user.token
          }
        }).then(res => {
          if (res.data.code === 1) {
            this.$message.success("员工状态修改成功！"),
            this.pageQuery()
          }
        }).catch(err => {
          this.$message.error('修改失败！')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    }
  }
}
</script>

<style scoped>
.el-input {
  width: 40%;
}
.el-icon-success{
  color: #1dc779;
}
.el-icon-error{
  color: #f56c6c;
}
.view {
  width: 96%;
  margin: 1% auto;
  border-radius: 10px;
  background-color: #ffffff;
  padding: 10px;
  overflow: hidden;
}

</style>
